//
//  HomeViewController.m
//  Text
//
//  Created by apple on 2017/10/9.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HomeViewController.h"

@interface HomeViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate>
{
    UIImageView *mapCenterImageView;
}
@property (nonatomic,strong) BMKMapView* mapView;
@property (nonatomic,strong) BMKLocationService* locService;
@property (nonatomic,assign) CLLocationCoordinate2D coordinate2D;
@property (nonatomic,strong) BMKPointAnnotation* pointAnnotation;
@property (nonatomic,strong) BMKAnnotationView* AnnotationView;
@property (nonatomic,assign) double latitude;
@property (nonatomic,assign) double longitude;
@end

@implementation HomeViewController

#pragma mark - life cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //初始化地图
    self.mapView = [[BMKMapView alloc] initWithFrame:self.view.frame];
    self.mapView.delegate =self;
    [self.view addSubview:self.mapView];
    
    //定位
    self.locService = [[BMKLocationService alloc]init];
    //设置代理
    self.locService.delegate = self;
   [self.locService startUserLocationService];
    NSLog(@"进入普通定位态");
    
    //视图
    UIButton *startLocationButton = [[UIButton alloc] init];
    startLocationButton.frame = CGRectMake(30, 60, 40, 40);
    [startLocationButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [startLocationButton setImage:[UIImage imageNamed:@"定位刷新"] forState:UIControlStateNormal];
    [startLocationButton addTarget:self action:@selector(startLocation:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startLocationButton];
    
    mapCenterImageView = [[UIImageView alloc] init];
    mapCenterImageView.center = self.view.center;
    mapCenterImageView.bounds = CGRectMake(0, 0, 25, 30);
    mapCenterImageView.image = [UIImage imageNamed:@"大头针"];
    [self.view addSubview:mapCenterImageView];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.mapView viewWillAppear];
    self.mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
-(void)viewWillDisappear:(BOOL)animated
{
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil; // 不用时，置nil
}

- (void)dealloc
{
    if (self.mapView) {
        self.mapView = nil;
    }
}


#pragma mark - BMKMapViewDelegate

//自定义定位view
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    
    //[self addPointAnnotation:centerCoordinate.latitude withLongitude:centerCoordinate.longitude];
    NSString *annotationViewID = @"renameMark";
    if (self.AnnotationView == nil) {
        self.AnnotationView = [[BMKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:annotationViewID];
        self.AnnotationView.image = [UIImage imageNamed:@"centerPost"];
        
    }
    
    return self.AnnotationView;
}

//位置更新
/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    //更新位置数据
    [self.mapView updateLocationData:userLocation];

    self.coordinate2D = userLocation.location.coordinate;

    static int i = 0;
    if (i == 0)
    {
        [self positioning];
        [self addPointAnnotation:userLocation.location.coordinate.latitude withLongitude:userLocation.location.coordinate.longitude];
        i++;
    }
    
}

//Map移动 后执行，所以我们可以在这里获取移动后地图中心点的经纬度了
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    
    BMKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center= centerCoordinate;
    
    NSLog(@" regionDidChangeAnimated %f,%f",centerCoordinate.latitude, centerCoordinate.longitude);
    
    //反地理编码：根据经纬度，得到对应的地理位置名称
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    CLLocation *location = [[CLLocation alloc]initWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks) {
//            NSDictionary *location =[place addressDictionary];
            NSDictionary *location =place.addressDictionary;
            NSLog(@"国家：%@",[location objectForKey:@"Country"]);
            NSLog(@"城市：%@",[location objectForKey:@"State"]);
            NSLog(@"区：%@",[location objectForKey:@"SubLocality"]);
            NSLog(@"位置：%@", place.name);
            NSLog(@"国家：%@", place.country);
            NSLog(@"城市：%@", place.locality);
            NSLog(@"区：%@", place.subLocality);
            NSLog(@"街道：%@", place.thoroughfare);
            NSLog(@"子街道：%@", place.subThoroughfare);
        }
    }];
    //做动画
    [self popJumpAnimationView:mapCenterImageView];
    
}


#pragma mark - Action

-(void)startLocation:(UIButton *)sender
{
    
    [self positioning];
}

#pragma mark - Private Method

//根据经纬度获取位置

//定位
-(void)positioning
{
    //开始定位
    [self.locService startUserLocationService];
    self.mapView.showsUserLocation = NO;//先关闭显示的定位图层
    self.mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    //    self.mapView.showsUserLocation = YES;//显示定位图层
    //获取用户的坐标
    self.mapView.centerCoordinate = self.coordinate2D;
    self.mapView.zoomLevel =16;
}

//添加标注
-(void)addPointAnnotation:(double)lat withLongitude:(double)lgt
{
    self.pointAnnotation = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coors2;
    coors2.latitude = lat;
    coors2.longitude = lgt;
    self.pointAnnotation.coordinate = coors2;
    self.pointAnnotation.title = @"我的位置";
    //  self.pointAnnotation.subtitle=@"这个注释可以拖拽哦!";
    [self.mapView addAnnotation:self.pointAnnotation];
    
}

//1.跳动效果的实现
- (void)popJumpAnimationView:(UIImageView *)sender
{
    
    CGFloat duration = 1.f;
    CGFloat height = 7.f;
    
    CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
    CGFloat currentTy = sender.transform.ty;
    animation.duration = duration;
    animation.values = @[@(currentTy), @(currentTy - height/4), @(currentTy-height/4*2), @(currentTy-height/4*3), @(currentTy - height), @(currentTy-height/4*3), @(currentTy -height/4*2), @(currentTy - height/4), @(currentTy)];
    animation.keyTimes = @[ @(0), @(0.025), @(0.085), @(0.2), @(0.5), @(0.8), @(0.915), @(0.975), @(1) ];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.repeatCount = 1;
    [sender.layer addAnimation:animation forKey:@"kViewShakerAnimationKey"];
    
}

#pragma mark - 定位开始和结束调用
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}



@end
